﻿(function (RMS) {
    //public properties
    var DynamicTemplate = function (settings) {
        this.init(settings);
    };
    var $entry,
        $template;
    var datetime;
    //======================================================
    DynamicTemplate.prototype.isCompleted = false;

    DynamicTemplate.prototype.init = function (settings) {
        if (settings) {
            this.settings = $.extend(true, {
                childName: 'items',
                meta: {
                    theme: {
                        level1: 'bootstrap',
                        level2: 'bootstrap'
                    },
                    breakByLevel: 2
                }
            }, settings);
        }
        $entry = $(this.settings.id);
        $entry.attr({ level: 0 });

        $template = $entry.clone();

        datetime = new Date().getTime();
        var _this = this;
        if (_this.settings.url) {
            RMS.Ajax({
                url: _this.settings.url,
                type: 'post',
                data: {},
                success: function (data) {
                    if (data) {
                        data = new RMS.CCSV2JSON(data).toJson();
                        if (data && data[1]) {
                            dynamic($entry, data, _this);
                        }
                    }
                }
            });
        }
        else if (_this.settings.data) {
            dynamic($entry, _this.settings.data, _this);
        }
        else {
            console.log('::data is undefined');
        }
    };

    DynamicTemplate.prototype.loadComplete = function (instance) {
        this.isCompleted = true;
        if (this.settings.callback) {
            this.settings.callback(instance);
        }
    };
    //private function  
    function dynamic($entry, data, instance) {
        data = RMS.pub.convert2TreeData(data, instance.settings.childName);
        //console.log(data);
        switch (instance.settings.type) {
            case 'nav': //nav tree
                dynamicNav($entry, data, instance);
                break;
            case 'nav1': //nav 1 level
                dynamicNav1($entry, data, instance);
                break;
            case 'menu': //menu tree
                dynamicMenu($entry.children(), data, instance);
                break;
            case 'product': //product
                dynamicProduct($entry, data, instance);
                break;
            case 'products': //product
                dynamicProducts($entry, data, instance);
                break;
            case 'cat': //categories
                dynamicCategories($entry, data, instance);
                break;
            case 'news': //news
                dynamicNews($entry, data, instance);
                break;
            default:

                break;
        }
        instance.loadComplete(instance);
        console.log('::end callback', new Date().getTime() - datetime);
    };

    function dynamicNav($entry, data, instance) {
        var html = $entry[0].innerHTML,
            $div = $('<div>'),
            $entryClone,
            $titleClone,
            $contentClone,
            titleHtml,
            contentHtml;

        $titleClone = $entry.find('div:first').clone(true);
        $contentClone = $entry.find('div:first').next().clone(true);

        titleHtml = $titleClone[0].innerHTML;
        contentHtml = $contentClone[0].innerHTML;

        $entry.empty();
        $entryClone = $entry.clone(true);

        getNavHtml($entry, data);

        console.log('::end generate', new Date().getTime() - datetime);

        function getNavHtml($p, data) {
            for (var i = 0; i < data.length; i++) {
                //header               
                $p.append(nano(titleHtml, data[i]));
                var $d = $div.clone();
                $p.append($d);
                if (data[i][instance.settings.childName] && data[i][instance.settings.childName].length) {
                    var $clone = $entryClone.clone();
                    //add current level
                    $clone.attr('level', data[i]._level + 1);
                    $d.append($clone);
                    getNavHtml($clone, data[i][instance.settings.childName]);
                }
            }

            var level = $p.attr('level'),
                settings = {};
            if (typeof level != 'undefined') {
                if (level > 0) {
                    settings.expandMode = 'single';
                }
                $p.removeAttr('level');
                if (instance.settings.meta && instance.settings.meta.theme) {
                    if (typeof instance.settings.meta.theme['level' + level] != 'undefined') {
                        settings.theme = instance.settings.meta.theme['level' + level];
                    }
                }
            }
            if (Object.keys(settings).length) {
                $p.attr(RMS.consts.settings, JSON.stringify(settings));
            }
        };
    };

    function dynamicNav1($entry, data, instance) {
        var html = $entry[0].innerHTML,
            $div = $('<div>'),
            $titleClone,
            $contentClone,
            titleHtml,
            contentHtml;

        $titleClone = $entry.find('div:first').clone(true);
        $contentClone = $entry.find('div:first').next().clone(true);

        titleHtml = $titleClone[0].outerHTML;
        contentHtml = $contentClone.find('ul')[0].innerHTML;

        $entry.empty();
        $titleClone.empty();
        $contentClone.find('ul').empty();

        getNav1Html($entry, data, titleHtml);

        console.log('::end generate', new Date().getTime() - datetime);

        function getNav1Html($p, data, template) {
            for (var i = 0; i < data.length; i++) {
                //header               
                $p.append(nano(template, data[i]));
                if (data[i][instance.settings.childName] && data[i][instance.settings.childName].length) {
                    var $clone = $contentClone.clone();
                    //add current level                    
                    $p.append($clone);
                    getNav1Html($clone.find('ul'), data[i][instance.settings.childName], contentHtml);
                }
            }
        };
    };

    function dynamicMenu($el, data, instance) {
        var html = $el[0].innerHTML,
            $elClone;

        $el.empty();
        $elClone = $el.clone();

        getMenuHtml($el, data);

        console.log('::end generate', new Date().getTime() - datetime);

        function getMenuHtml($p, data) {
            for (var i = 0; i < data.length; i++) {
                $p.append(nano(html, data[i]));
                if (data[i][instance.settings.childName] && data[i][instance.settings.childName].length) {
                    var $clone = $elClone.clone();
                    //add current level
                    $clone.attr('level', data[i]._level + 1);
                    $p.find('li#' + data[i].ID).append($clone);
                    getMenuHtml($clone, data[i][instance.settings.childName]);
                }
            }
        };
    };

    function dynamicProduct($el, data, instance) {
        console.log('product')
    };

    function dynamicProducts($el, data, instance) {
        console.log('products')
    };

    function dynamicCategories($el, data, instance) {
        console.log('Categories')
    };

    function dynamicNews($el, data, instance) {
        console.log('News')
    };

    function nano(template, data) {
        return template.replace(/\{([\w\.]*)\}/gi, function (str, key) {
            var keys = key.split("."), v = data[keys.shift()];
            for (var i = 0; i < keys.length; i++) v = v[this];
            return (typeof v !== "undefined" && v !== null) ? v : "";
        });
    };

    RMS.CDynamicTemplate = DynamicTemplate;
})(RMS);